import Vue from "vue";
import VueRouter, {RouteConfig} from "vue-router";
import store from '@/store';

Vue.use(VueRouter);

const routes: Array<RouteConfig> = [
    {
        path: '/login',
        name: 'login',
        meta: {
            title: '登录'
        },
        component: () => import(/* webpackChunkName: "guide" */ "@/views/guide/index.vue"),
    },
    {
        path: '/home',
        name: 'home',
        meta: {
            title: '主页',
            token: true
        },
        component: () => import(/* webpackChunkName: "guide" */ "@/views/guide/index.vue"),
    }
];

const router = new VueRouter({
    routes
});
/**
 * 是否同时存在token和需要校验token,
 * key由 是否需要token + 是否有token 组成
 * */
const judgment = new Map();

judgment.set('true|true', '');
judgment.set('true|false', '/login');
judgment.set('false|true', '');
judgment.set('false|false', '');

router.beforeEach((to, form, next) => {
    if (to.path === '/login') {
        next()
    } else {
        const key = to.meta.token !== undefined && to.meta.token.toString() + '|' + store.state.user.token && store.state.user.token !== ''
        next(judgment.get(key) || '/login');
    }

    if (to.meta.token) {
        if (store.state.user.token) {
            next()
        } else {
            next('/login')
        }
    } else {
        next();
    }
});

export default router;
